import {ADDTOCART, UPDATEGOODSNUM, UPDATEGOODSCHECKED, SETALLCHECKED, DELETEGOODS} from './actions';

const cart = {
    namespaced: true,
    state: {
        cartList: []
    },
    mutations: {
        [ADDTOCART](state, payload) {
            const goodsIndex = state.cartList.findIndex(item => item.id === payload.id)
            if (goodsIndex === -1) {
                const newGoods = {
                    count: 1,
                    ...payload
                }
                state.cartList.push(newGoods);
            } else {
                state.cartList[goodsIndex].count += 1;
            }
        },
        [UPDATEGOODSNUM](state, payload) {
            const goodsIndex = state.cartList.findIndex(item => item.id === payload.id);
            state.cartList[goodsIndex].count = payload.count;
        },
        [UPDATEGOODSCHECKED](state, payload) {
            const goodsIndex = state.cartList.findIndex(item => item.id === payload.id);
            state.cartList[goodsIndex].checked = payload.checked;
        },
        [SETALLCHECKED](state, payload) {
            state.cartList = state.cartList.map(item => {
                item.checked = payload
                return item
            })
        },
        [DELETEGOODS](state, payload) {
            const goodsIndex = state.cartList.findIndex(item => item.id === payload);
            state.cartList.splice(goodsIndex, 1);
        }
    },
    actions: {},
    getters: {
        totalPrice(state) {
            let result = 0;
            state.cartList.forEach(item => {
                if (item.checked) {
                    result += item.count * item.price
                }
            })
            return result
        }
    }
}

export default cart